package com.csi.jf.crucible.ptservice.controller;

import java.io.IOException;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chinasofti.ro.bizframework.core.data.validation.Validation;
import com.chinasofti.ro.bizframework.core.mvc.Controller;
import com.chinasofti.ro.bizframework.core.mvc.View;
import com.chinasofti.ro.bizframework.core.orm.Page;
import com.chinasofti.ro.bizframework.core.orm.PageUtil;
import com.chinasofti.ro.bizframework.core.orm.entity.Model;
import com.chinasofti.ro.bizframework.modules.json.JSONObject;
import com.csi.jf.crucible.api.crucible.ApiTestProject;
import com.csi.jf.crucible.api.crucible.ApiTestRepository;
import com.csi.jf.crucible.api.crucible.ApiTestReviews;
import com.csi.jf.crucible.api.crucible.ReviewModel;
import com.csi.jf.crucible.api.util.ApiUtils;
import com.csi.jf.crucible.api.util.StringUtils;
import com.csi.jf.crucible.common.config.JfConstants;
import com.csi.jf.crucible.common.util.LoginUtils;
import com.csi.jf.crucible.ptservice.model.CruReviews;
import com.csi.jf.crucible.ptservice.model.PrjAssociate;
import com.csi.jf.crucible.ptservice.model.ServiceOrders;
import com.csi.jf.crucible.ptservice.service.CruReviewsService;
import com.csi.jf.crucible.ptservice.service.PrjAssociateService;
import com.csi.jf.crucible.ptservice.service.ServiceOrdersService;
import com.icss.j2ee.util.http.HttpClientException;

/**
 * <p>Controller</p>
 * 
 * @author BizFoundation
 * @version 1.0
 * @since 1.0
 */
public class ServiceOrdersController extends Controller {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * <p>打开查询列表页面</p>
	 * 
	 */
	public void list() {
		this.render(SUCCESS);
	}

	/**
	 * <p>查询分页数据</p>
	 * @param gridPage
	 * @param pTSservice
	 */
	public void listServiceOrders(Page page,ServiceOrders pTSservice) {
		HttpSession session = request().getSession(false);
		
		page = serviceOrdersService.findByPage(pTSservice, page, String.valueOf(session.getAttribute(JfConstants.PROJECT_ID)));
		this.renderJSON(PageUtil.toJson4JqGrid(page, true));
	}
	public void show(Long id) {
		if(null == id){
			throw new NullPointerException("主键为Null");
		}
		Model pTSservice = serviceOrdersService.findById(id);
		View view = new View(SUCCESS);
		view.bind("pTSservice",pTSservice);
		this.render(view);
	}

	 public void save(ServiceOrders pTSservice) throws HttpClientException, IOException {
		if (Validation.hasErrors()) {
			this.printError(Validation.getErrorsAsString());
			return;
		}

//		 Long professorId=LoginUtils.getLoginUser().getJfid();
		Long professorId=4L; //FIXME hard code here temporary
		 if(null!=professorId){
			 pTSservice.setProfessorID(professorId);
		 }
		 String projectName=LoginUtils.getCurrentProject().getProjectName();
		 pTSservice.setCreator(LoginUtils.getLoginUser().getUserName());
		 pTSservice.setProjectName(projectName);
		 serviceOrdersService.save(pTSservice);
		 
		 
		//save project Info about crucible
		PrjAssociate pa = new PrjAssociate();
		Long prjJfId = pTSservice.getProjectId();
		pa.setPrjJfId(prjJfId);
//		String prjCruName = ;
		pa.setPrjCruName(ApiUtils.getCruProjectName(projectName));
		String prjCruKey = ApiUtils.getCruKeyByProjectId(prjJfId);
		pa.setPrjCruKey(prjCruKey);
//		String prjSonarKey = ;
		pa.setPrjSonarKey(ApiUtils.getSonarKeyByProjectId(prjJfId));
		pa.setRepoName(ApiUtils.getCruRepo(projectName));
		PrjAssociate paDb = (PrjAssociate)prjAssociateService.findByJfId(prjJfId);
		//if the record with the project was inserted successfully in the table jf_pts_project_associate
		//don't insert it again, check whether the project was created in crucible only
		ApiTestProject test = new ApiTestProject();
		String moderatorName = "jfpts";
		String moderatorEmail = "jfpts@chinasofti.com";
		//create repository in crucible , if repo was not created , create it now
		ApiTestRepository testRepo = new ApiTestRepository();
		testRepo.createRepository(StringUtils.replaceEmailAt(moderatorEmail), pa.getRepoName());
		
		if(paDb == null || paDb.getId() == null) {
			test.createProject(pa.getPrjCruName(), pa.getPrjCruKey(), pa.getRepoName(), moderatorName);
			prjAssociateService.save(pa);
		} else {
			pa = paDb;
			if(pa.getRepoName() == null) {
				pa.setRepoName(ApiUtils.getCruRepo(projectName));
				prjAssociateService.update(pa);
			}
			test.createProject(pa.getPrjCruName(), pa.getPrjCruKey(), pa.getRepoName(), moderatorName);
		}
		
		
		//save review info into database
		CruReviews cr = new CruReviews();
		cr.setPrjJfId(prjJfId);
		cr.setPrjCruId(pa.getId());
		cr.setPrjCruKey(prjCruKey);
		cr.setReviewName(pTSservice.getProjectName() + pTSservice.getServiceName());
		
		
		//create a review in crucible
		ApiTestReviews testReview = new ApiTestReviews();
		String projectKey = prjCruKey;
		String name = cr.getReviewName();
		String description = "";
		JSONObject author = new JSONObject();
		author.put("userName", "zhangmh");
		author.put("displayName", "zhang.m.h");
		author.put("avatarUrl", "http://foo.com/avatar");
		
		JSONObject moderator = new JSONObject();
		moderator.put("userName", moderatorName);
		moderator.put("displayName", "jf pts");
		moderator.put("avatarUrl", "http://foo.com/avatar");
		
		JSONObject creator = new JSONObject();
		creator.put("userName", moderatorName);
		creator.put("displayName", "jf pts");
		creator.put("avatarUrl", "http://foo.com/avatar");
		
		JSONObject permaId = new JSONObject();
		permaId.put("id", "PTS-TEST-21");
		
		JSONObject changesets = new JSONObject();
		changesets.put("changesetData", "[]");
		changesets.put("repository", pa.getRepoName());
//		creator.put("repository", "CrucibleTest");
		
		ReviewModel rm = new ReviewModel(projectKey, name, description, author, moderator, creator, permaId, changesets);
		String reviewJson = rm.createReviewModel();
		//拿到返回的permaId即reviewId 并存入数据表中
	    String reviewId=testReview.createReview(reviewJson,pa);
	    cr.setReviewId(reviewId);
	    cruReviewsService.save(cr);
	    
	    //更新服务订单的reviewId与review表关联
	    pTSservice.setReviewId(reviewId);
	    serviceOrdersService.update(pTSservice);
	    
	    
	}

	public void edit(Long id) {
		if(null == id){
			throw new NullPointerException("主键为Null");
		}
		Model pTSservice = serviceOrdersService.findById(id);
		this.renderJSON(pTSservice.toJson());
	}

	public void update(ServiceOrders pTSservice) {
		serviceOrdersService.update(pTSservice);
		this.renderJSON(pTSservice);
	}

	public void delete(String ids) {
		this.serviceOrdersService.batchDelete(ids);
	}
    
	/**
	 * <p>显示列表</p>
	 * 
	 */
	public void index() {
		View view = new View(SUCCESS);
		this.render(view);
	}
	
	/**
	 * 申请服务
	 * 
	 * @param serviceID
	 * @Created on 2014-7-3 下午10:39:05
	 * @author FengHaiBing
	 */
	public void applyService(Long serviceID) {
		
		View view = new View(SUCCESS);
		this.render(view);
	}
	
    /**
     * <p>注入 pTSserviceService</p>
     */
    private ServiceOrdersService serviceOrdersService;
    
    /**
     * <p>注入 prjAssociateService</p>
     */
    private PrjAssociateService prjAssociateService;
    
    /**
     * <p>注入 reviewCruService</p>
     */
	private CruReviewsService cruReviewsService;

    public void setPrjAssociateService(PrjAssociateService prjAssociateService) {
		this.prjAssociateService = prjAssociateService;
	}

	public void setCruReviewsService(CruReviewsService cruReviewsService) {
		this.cruReviewsService = cruReviewsService;
	}

	public void setServiceOrdersService(ServiceOrdersService serviceOrdersService) {
		this.serviceOrdersService = serviceOrdersService;
	}
	
}